import 'dart:convert';

import '../../config/config.dart';
import '../../hj_model/splash/ads_model.dart';
import '../../hj_utils/light_model.dart';
import '../../hj_utils/text_util.dart';

/// 不含状态的本地存储，主要是lightmodel的序列化存储

///根据位置获取某一个广告数据
///1 启动页
// 2 九宫格广告
// 3 九宫格横幅广告
// 4 首页公告弹窗
// 5 首页轮播广告
// 6 首页推荐-本周推荐下方轮播图
// 7 ACG轮播广告
// 8 原味轮播图
// 9 原味-活动轮播图
// 10 国产轮播图
// 12 长视频播放页广告

Future<List<AdsInfoModel>> getAdvByType(int? position) async {
  if (null == position) return [];
  List<AdsInfoModel>? resultList = await LocalAdsStore().getAllAds();
  print('resultList ${resultList?.map((e) => e.position).toList().asMap()}');
  if (resultList?.isNotEmpty != true) return <AdsInfoModel>[];

  List<AdsInfoModel>? newList = resultList?.where((it) => it.position == position).toList();
  return newList ?? [];
}

List<AdsInfoModel> getAdvByTypeSync(int? position) {
  if (null == position) return [];
  List<AdsInfoModel>? resultList = LocalAdsStore().adsList;
  if (resultList?.isNotEmpty != true) return <AdsInfoModel>[];

  List<AdsInfoModel>? newList = resultList?.where((it) => it.position == position).toList();
  return newList ?? [];
}

Future<List<AdsInfoModel>> getAdvBeforeByType(int? position) async {
  if (null == position) return [];
  String? localAdsStr = await lightKV.getString("_key_ads_list${Config.DEBUG}");
  List<AdsInfoModel>? resultList;
  try {
    if (TextUtil.isNotEmpty(localAdsStr)) {
      resultList = (jsonDecode(localAdsStr!) as List?)?.map((o) => AdsInfoModel.fromMap(o)).toList();
    }
  } catch (_) {}
  if (resultList?.isNotEmpty != true) return <AdsInfoModel>[];
  List<AdsInfoModel>? newList = resultList?.where((it) => it.position == position).toList();
  return newList ?? [];
}

class LocalAdsStore {
  static LocalAdsStore? _instance;
  factory LocalAdsStore() {
    _instance ??= LocalAdsStore._();
    return _instance!;
  }

  LocalAdsStore._();
  List<AdsInfoModel>? adsList;

  ///获取本地存储的TAG信息
  Future<List<AdsInfoModel>?> getAllAds() async {
    if (adsList?.isNotEmpty == true) return adsList;
    // 非共享key
    String? localAdsStr = await lightKV.getString("_key_ads_list${Config.DEBUG}");
    try {
      if (TextUtil.isNotEmpty(localAdsStr)) {
        adsList = (jsonDecode(localAdsStr!) as List?)?.map((o) => AdsInfoModel.fromMap(o)).toList();
      }
    } catch (_) {}
    return adsList;
  }

  Future<bool?> setAdsList(List<AdsInfoModel>? ads) async {
    //if (ads?.isNotEmpty != true) return false;
    try {
      adsList = ads;
      String jsonStr = json.encode(ads);
      if (TextUtil.isEmpty(jsonStr)) return false;
      // 非共享key
      return lightKV.setString("_key_ads_list${Config.DEBUG}", jsonStr);
    } catch (e) {
      return false;
    }
  }

  ///清除记录
  clean() {
    lightKV.setString("_key_ads_list${Config.DEBUG}", "");
  }
}
